const { Repair, RepairPart, sequelize } = require('../common/mysql.js')
const { Op } = require('sequelize')

exports.insert = async (repair, store_id) => {
    let transaction
    try {
        transaction = await sequelize.transaction()
        const insertRepair = await Repair.create(repair, {
            transaction
        })
        if (repair.type === 1) {
            for (let i in repair.RepairParts) {
                repair.RepairParts[i].repair_id = insertRepair.id
                repair.RepairParts[i].store_id = store_id
                await RepairPart.create(repair.RepairParts[i], {
                    transaction
                })
            }
        }
        await transaction.commit()
    } catch (e) {
        await transaction.rollback()
        throw new Error('插入数据库失败')
    }
}

exports.update = async (id, repair, store_id) => {
    let transaction
    try {
        const fields = ['fault', 'detail', 'date', 'status', 'type', 'remark']
        if (repair.type === 2) {
            fields.push('serial')
        }
        transaction = await sequelize.transaction()
        await Repair.update(repair, {
            fields,
            where: {
                id: {
                    [Op.eq]: id
                }
            },
            transaction
        })
        if (repair.type === 1) {
            for (let i in repair.RepairParts) {
                repair.RepairParts[i].store_id = store_id
                if (repair.RepairParts[i].id) {
                    await RepairPart.update(repair.RepairParts[i], {
                        where: {
                            id: {
                                [Op.eq]: repair.RepairParts[i].id
                            }
                        },
                        fields: ['part_id', 'count'],
                        transaction
                    })
                } else {
                    repair.RepairParts[i].repair_id = id
                    await RepairPart.create(repair.RepairParts[i], {
                        transaction
                    })
                }
            }
        }
        await transaction.commit()
    } catch (e) {
        console.log(e)
        await transaction.rollback()
        throw new Error('更新失败')
    }
}

exports.del = async id => {
    await Repair.destroy({
        where: {
            id: {
                [Op.eq]: id
            }
        }
    })
}

exports.getOne = async id => {
    return await Repair.findOne({
        include: [
            {
                model: RepairPart
            }
        ],
        where: {
            id: {
                [Op.eq]: id
            }
        }
    })
}
